<template>
  <div>
  <!-- 富文本编辑器, 容器 -->
  <div :id="'J_quillEditor'+uuid" :style="'height:'+height+';width:'+width"></div>
  <el-upload
          action="#"
          multiple
          :show-file-list="false"
          :before-upload="uploadBeforeUploadHandle"
          :http-request="uploadSectionFileText"
          style="display: none;">
    <el-button ref="uploadBtn" type="primary" size="small">{{ $t('upload.button') }}</el-button>
  </el-upload>
    <!--<vue-quill-editor v-model="content" :options="{modules: {toolbar: quillEditorToolbarOptions}}"></vue-quill-editor>-->
  </div>
</template>
<script>
import Cookies from 'js-cookie'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import Quill from 'quill'
import { getUUID } from '@/utils'
/* import { quillEditor } from 'vue-quill-editor' */
import ImageResize from 'quill-image-resize-module'
Quill.register('modules/imageResize', ImageResize) // 添加

let quillEditorToolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
  ['blockquote', 'code-block'], // 引用，代码块

  [{ 'header': 1 }, { 'header': 2 }], // 标题，键值对的形式；1、2表示字体大小
  [{ 'list': 'ordered' }, { 'list': 'bullet' }], // 列表
  [{ 'script': 'sub' }, { 'script': 'super' }], // 上下标
  [{ 'indent': '-1' }, { 'indent': '+1' }], // 缩进
  [{ 'direction': 'rtl' }], // 文本方向

  [{ 'size': ['small', false, 'large', 'huge'] }], // 字体大小
  [{ 'header': [1, 2, 3, 4, 5, 6, false] }], // 几级标题

  [{ 'color': [] }, { 'background': [] }], // 字体颜色，字体背景颜色
  [{ 'font': [] }], // 字体
  [{ 'align': [] }], // 对齐方式

  ['clean'], // 清除字体样式
  ['image'] // 上传图片、上传视频
]
export default {
  data () {
    return {
      content: '', /* 内容 */
      quillEditorToolbarOptions: [],
      uuid: getUUID()
    }
  },
  props: {
    readOnly: {
      type: Boolean,
      default: false
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '500px'
    }
  },
  methods: {
    init (content) {
      this.content = content
      // 实例化富文本编辑器
      this.$nextTick(() => {
        // 富文本修改或新增
        if (this.quillEditor) {
          /* this.quillEditor.deleteText(0, this.quillEditor.getLength()) */
          if (this.content) {
            this.content = this.content.replace(/<p class="ql-align-justify" style="line-height:0;">/g, '<p class="ql-align-justify">')
          }
          this.quillEditor.root.innerHTML = this.content
        } else {
          this.quillEditorHandle()
        }
      })
    },
    // 富文本编辑器
    quillEditorHandle () {
      let theme = ''
      if (this.readOnly) {
        theme = 'bubble'
      } else {
        theme = 'snow'
        this.quillEditorToolbarOptions = quillEditorToolbarOptions
      }

      this.quillEditor = new Quill('#J_quillEditor' + this.uuid, {
        modules: {
          toolbar: this.quillEditorToolbarOptions,
          imageResize: {
            modules: [ 'Resize' ]
          }
        },
        theme: theme,
        readOnly: this.readOnly
      })
      // 初始赋值
      this.quillEditor.root.innerHTML = this.content
      // 自定义上传图片功能 (使用element upload组件)
      this.uploadUrl = `${window.SITE_CONFIG['apiURL']}/oss/file/upload?token=${Cookies.get(this.$config.tokenKeySign + 'token')}`
      this.quillEditor.getModule('toolbar').addHandler('image', () => {
        this.$refs.uploadBtn.$el.click()
      })
      // 监听内容变化，动态赋值
      this.quillEditor.on('text-change', () => {
        this.content = this.quillEditor.root.innerHTML
        if (this.content) {
          this.content = this.content.replace(/<p class="ql-align-justify">/g, '<p class="ql-align-justify" style="line-height:0;">')
        }
        this.$emit('update:value', this.content)
      })
    },
    // 上传图片之前
    uploadBeforeUploadHandle (file) {
      if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
        this.$message.error('只支持jpg、png、gif格式的图片！')
        return false
      }
    },
    // 富文本编辑器，图片上传
    uploadSectionFileText: function (file) {
      var formDate = new FormData()
      formDate.append('file', file.file)
      this.$http.post(this.uploadUrl, formDate, { isNotEncrypt: true }).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.quillEditor.insertEmbed(this.quillEditor.getSelection().index, 'image', window.SITE_CONFIG['dominURL'] + res.data.url)
      })
    }
  }
}
</script>
